package com.cavy.platform.server.domain;

import com.cavy.platform.server.domain.job.Job;
import com.cavy.platform.server.domain.message.HeartbeatMessage;
import com.cavy.platform.server.domain.message.JobDispatchMessage;
import com.cavy.platform.server.service.AgentSessionService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import static java.util.Calendar.SECOND;

/**
 * @author 唐旭
 * @Date 2018/7/24
 */
@Data
@Slf4j
public class AgentOnline {
    private Agent info;
    private Session session;
    private long memoryUsed;
    private int jobCount;
    private Date lastHeartbeatTime = new Date();

    public AgentOnline(Agent info, Session session) {
        this.info = info;
        this.session = session;
    }

    public void heartbeat(HeartbeatMessage message) {
        memoryUsed = message.getMemoryUsed();
        jobCount = message.getJobCount();
        lastHeartbeatTime = new Date();
    }

    public void sendJob(Job job) throws IOException {
        session.getBasicRemote().sendText(new JobDispatchMessage(job).toJson());
        info.addJob(job);
    }

    public boolean available() {
        if (!info.available()) {
            return false;
        }
        if (jobCount >= info.getMaxJobCount()) {
            return false;
        }
        return true;
    }

//    public void stopAll(Session session) throws IOException {
//        List<JobId> jobList = info.getJobList();
//        for (JobId job : jobList) {
//            session.getBasicRemote().sendText(new JobStopMessage(job).toJson());
//            info.stop(job);
//        }
//    }

    public boolean isOffLine(AgentConfig agent) {
        int maxHeartbeatCycle = agent.getMaxHeartbeatCycle();
        Calendar instance = Calendar.getInstance();
        instance.setTime(lastHeartbeatTime);
        instance.add(SECOND, maxHeartbeatCycle * AgentSessionService.FIXED_RATE / 1000);
        Date time = instance.getTime();
        //容忍时间在当前时间以后
        return new Date().after(time);
    }

    /**
     * agent离线 更新离线时间
     */
    public void offLine() {
        info.updateLastHeartbeatTime(this.lastHeartbeatTime);
    }
}
